import { constantRoutes } from '@/router'
import { isExternal } from '@/utils/validate'

function recursiveRoutes(routes, app) {
  for (const route of routes) {
    route.component = resolve => require([`@/views${route.menuFilePath}`], resolve)
    // 第一层菜单的外部链接
    if (route.path.startsWith('/') && isExternal(route.path.slice(1))) route.path = route.path.slice(1)

    if (route.children && route.children.length > 0) recursiveRoutes(route.children)
  }
  return routes
}

const state = {
  routes: [],
  platforms: [],
  menus: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_PLATFORMS: (state, routes) => {
    state.platforms = routes
  },
  SET_MENUS: (state, routes) => {
    state.menus = routes
  },
  CLEAR_ROUTES: (state) => {
    state.addRoutes = []
    state.routes = []
  }
}

const actions = {
  generateRoutes({ commit }, routes) {
    return new Promise(resolve => {
      // const data = recursiveRoutes(routes)
      const data = []
      data.push({ path: '*', redirect: '/404', hidden: true })
      commit('SET_ROUTES', data)
      commit('SET_PLATFORMS', routes) // 设置平台
      commit('SET_MENUS', routes[0].menus) //  // 设置菜单
      resolve(data)
    })
  },
  menus({ commit }, routes) {
    commit('SET_MENUS', routes)
  },
  clearRoutes({ commit }) {
    commit('CLEAR_ROUTES')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
